var loginToken = "";
$(function() {
	validateKickout();
    validateRule();
	$('.imgcode').click(function() {
		var url = ctx + "captcha/captchaImage?type=" + captchaType + "&s=" + Math.random();
		$(".imgcode").attr("src", url);
	});
});

$.validator.setDefaults({
    submitHandler: function() {
		login();
    }
});

function login() {
	$.modal.loading($("#btnSubmit").data("loading"));
	var username = $.common.trim($("input[name='username']").val());
    var password = $.common.trim($("input[name='password']").val());
    $.ajax({
        type: "post",
        url: ctx + "login",
        data: {
            "username": username,
            "password": password
        },
        success: function(r) {
            if (r.code === 200) {
                loginToken = r.result.token;
                loginSuccess()
                //departConfirm(r)
            } else {
            	$.modal.closeLoading();
            	$.modal.msg(r.message);
            }
        }
    });
}

function departConfirm(res) {

    let multi_depart = res.result.multi_depart
    //0:无部门 1:一个部门 2:多个部门
    if(multi_depart===0){
        $.modal.closeLoading();
        $.modal.msg("您尚未归属部门,请确认账号信息");
    }else if(multi_depart===2){
        $.modal.closeLoading();
        $.modal.open('您隶属于多部门，请选择登录部门', ctx + "selectDepart?token="+ loginToken +"&userId=" + res.result.userInfo.userid, '400', '200', callback);
        $("#layui-layer1").css("top", "160px");
    }else {
        loginSuccess()
    }
}

function callback(index, layero) {
    var form = $(layero).find("iframe")[0].contentWindow.document.getElementById("form-select-depart")
    $.ajax({
        url: ctx + "selectDepart",
        type: 'post',
        dataType: 'json',
        data: $(form).serialize(),
        beforeSend: function (request) {
            request.setRequestHeader("X-Access-Token", loginToken);
        },
        success: function(result) {
            if(result.success){
                loginSuccess();
            }else{
                $.modal.msg(result.message);
            }
        }
    });
}


function loginSuccess() {
    if(window.localStorage.getItem("token")){
        window.localStorage.removeItem("token");
    }
    window.localStorage.setItem("token",loginToken);
    location.href = ctx + 'index?token=' + loginToken;
}

function validateRule() {
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#signupForm").validate({
        rules: {
            username: {
                required: true
            },
            password: {
                required: true
            }
        },
        messages: {
            username: {
                required: icon + "请输入您的用户名",
            },
            password: {
                required: icon + "请输入您的密码",
            }
        }
    })
}

function validateKickout() {
	if (getParam("kickout") == 1) {
	    layer.alert("<font color='red'>您已在别处登录，请您修改密码或重新登录</font>", {
	        icon: 0,
	        title: "系统提示"
	    },
	    function(index) {
	        //关闭弹窗
	        layer.close(index);
	        if (top != self) {
	            top.location = self.location;
	        } else {
	            var url  =  location.search;
	            if (url) {
	                var oldUrl  = window.location.href;
	                var newUrl  = oldUrl.substring(0,  oldUrl.indexOf('?'));
	                self.location  = newUrl;
	            }
	        }
	    });
	}
}

function getParam(paramName) {
    var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
}